import { defineStore } from 'pinia'
import { computed, reactive, ref } from 'vue'

// 固定题库的题目接口
interface FixedQuestion {
  id: string | number
  content: string
  type: string
  questionType: string
  difficulty: number
  score: number // 题目分值
  partialScore?: number // 特殊分值（多选题漏选分值或填空题每空分值）
}

// 随机题库的题库接口
interface RandomBank {
  type: number
  name: string
  single: number
  multiple: number
  judge: number
  blank: number
  short: number
}

// 随机题库的抽取设置接口
interface RandomSettings {
  counts: {
    single: number
    multiple: number
    judge: number
    blank: number
    short: number
  }
  scores: {
    single: number
    multiple: number
    judge: number
    blank: number
    short: number
  }
  partialScores: {
    multiple: number
    blank: number
  }
}

// 添加固定题库分值设置的接口
interface ScoreSettings {
  typeScores: {
    [key: string]: number // 每种题型的分值
    blank_partial?: number // 填空题每空分值
    multiple_partial?: number // 多选题漏选分值
  }
  dialogTotalScore: number
}

// 修改 QuestionVO 类型定义
interface QuestionVO {
  id: string | number
  content: string
  type: string
  questionType: string
  difficulty: number
  score: number // 题目分值
  partialScore?: number // 特殊分值（多选题漏选分值或填空题每空分值）
  // ... 其他字段
}

// 修改排序状态的接口
interface SortState {
  prop: string | null
  order: 'ascending' | 'descending' | null
}

// 添加题型配置
const QUESTION_TYPE_CONFIG = {
  single: '单选题',
  multiple: '多选题',
  judge: '判断题',
  short: '简答题',
  blank: '填空题'
}

export const examPaperStore = defineStore('paper', () => {
  // 固定题库相关
  const fixedQuestions = ref<FixedQuestion[]>([])

  // 随机题库相关
  const randomBanks = ref<RandomBank[]>([])
  const randomSettings = reactive<RandomSettings>({
    counts: {
      single: 0,
      multiple: 0,
      judge: 0,
      blank: 0,
      short: 0
    },
    scores: {
      single: 0,
      multiple: 0,
      judge: 0,
      blank: 0,
      short: 0
    },
    partialScores: {
      multiple: 0,
      blank: 0
    }
  })

  // 添加固定题库分值设置
  const scoreSettings = reactive<ScoreSettings>({
    typeScores: {},
    dialogTotalScore: 0
  })

  // 添加排序状态
  const sortState = reactive<SortState>({
    prop: null,
    order: null
  })

  // 固定题库方法
  const setFixedQuestions = (questions: FixedQuestion[]) => {
    fixedQuestions.value = questions
  }

  const clearFixedQuestions = () => {
    fixedQuestions.value = []
  }

  const updateFixedQuestionScore = (type: string, score: number) => {
    fixedQuestions.value.forEach((question) => {
      if (question.type === type) {
        question.score = score
      }
    })
  }

  const updateFixedQuestionPartialScore = (type: string, score: number) => {
    fixedQuestions.value.forEach((question) => {
      if (question.type === type) {
        question.partialScore = score
      }
    })
  }

  const validateFixedQuestionPartialScore = (type: string) => {
    const questions = fixedQuestions.value.filter((q) => q.type === type)
    if (!questions.length) return true

    const score = questions[0].score
    const partialScore = questions[0].partialScore || 0

    if (partialScore > score) {
      updateFixedQuestionPartialScore(type, score)
      return false
    }
    return true
  }

  const calculateFixedTotalScore = () => {
    return Number(
      fixedQuestions.value.reduce((sum, question) => sum + (question.score || 0), 0).toFixed(1)
    )
  }

  // 随机题库方法
  const setRandomBanks = (banks: RandomBank[]) => {
    randomBanks.value = banks
  }

  const addRandomBank = (bank: RandomBank) => {
    randomBanks.value.push(bank)
  }

  const removeRandomBank = (index: number) => {
    randomBanks.value.splice(index, 1)
  }

  const clearRandomBanks = () => {
    randomBanks.value = []
  }

  const updateRandomSettings = (settings: Partial<RandomSettings>) => {
    Object.assign(randomSettings, settings)
  }

  // 清空所有数据
  const clearAll = () => {
    fixedQuestions.value = []
    randomBanks.value = []
    randomSettings.counts = {
      single: 0,
      multiple: 0,
      judge: 0,
      blank: 0,
      short: 0
    }
    randomSettings.scores = {
      single: 0,
      multiple: 0,
      judge: 0,
      blank: 0,
      short: 0
    }
    randomSettings.partialScores = {
      multiple: 0,
      blank: 0
    }
  }

  // 修改排序状态的更新方法
  const updateSortState = (prop: string | null, order: 'ascending' | 'descending' | null) => {
    // 如果是同一个字段，且状态为 null，则重置排序
    if (prop === sortState.prop && order === null) {
      sortState.prop = null
      sortState.order = null
      return
    }

    // 更新排序状态
    sortState.prop = prop
    sortState.order = order

    // 获取排序后的数据并更新 fixedQuestions
    if (prop && order) {
      const sorted = getSortedQuestions.value
      if (Array.isArray(sorted)) {
        fixedQuestions.value = sorted
      }
    }
  }

  // 获取题型标签
  const getQuestionTypeLabel = (type: string): string => {
    return QUESTION_TYPE_CONFIG[type] || '未知题型'
  }

  // 修改排序逻辑
  const getSortedQuestions = computed<FixedQuestion[]>(() => {
    // 确保 fixedQuestions 是数组
    if (!Array.isArray(fixedQuestions.value)) {
      return []
    }

    // 创建数组副本
    const questions = [...fixedQuestions.value]

    // 如果没有排序条件，返回原始数组的副本
    if (!sortState.prop || !sortState.order) {
      return questions
    }

    // 进行排序
    return questions.sort((a, b) => {
      const aValue = a[sortState.prop!]
      const bValue = b[sortState.prop!]

      // 对特殊字段进行处理
      switch (sortState.prop) {
        case 'type': {
          const aLabel = QUESTION_TYPE_CONFIG[aValue] || ''
          const bLabel = QUESTION_TYPE_CONFIG[bValue] || ''
          return sortState.order === 'ascending'
            ? aLabel.localeCompare(bLabel)
            : bLabel.localeCompare(aLabel)
        }
        case 'difficulty': {
          const numA = Number(aValue)
          const numB = Number(bValue)
          return sortState.order === 'ascending' ? numA - numB : numB - numA
        }
        default:
          return sortState.order === 'ascending'
            ? String(aValue).localeCompare(String(bValue))
            : String(bValue).localeCompare(String(aValue))
      }
    })
  })

  return {
    // 固定题库
    fixedQuestions,
    setFixedQuestions,
    clearFixedQuestions,
    updateFixedQuestionScore,
    updateFixedQuestionPartialScore,
    validateFixedQuestionPartialScore,
    calculateFixedTotalScore,

    // 随机题库
    randomBanks,
    randomSettings,
    setRandomBanks,
    addRandomBank,
    removeRandomBank,
    clearRandomBanks,
    updateRandomSettings,

    // 新的清空方法
    clearAll,

    // 排序状态
    sortState,
    updateSortState,
    getSortedQuestions,
    getQuestionTypeLabel
  }
})
